package usables;

import org.xml.sax.*;             
import org.xml.sax.helpers.*;   
import org.xml.sax.InputSource;

import handler.PhotoHandler;

import java.io.*;                 
import java.util.*;               
import org.xmldb.api.base.*;
import org.xmldb.api.base.Collection;
import org.xmldb.api.modules.*;
import org.xmldb.api.*;
import org.exist.xmldb.XQueryService;

import structures.Photo;


public class UsingPhotoHandler {
	
	public static void main(String[] args) throws Exception {
	
	// Here we will store the Photo objects
	Map<String, Photo> photos = new HashMap<String, Photo>();	    

	// Initialize the driver of the database
	String driver = "org.exist.xmldb.DatabaseImpl";
        String URI = "xmldb:exist://localhost:8080/exist/xmlrpc/db/DatabaseApplication";
        Class cl = Class.forName(driver);			
        Database database = (Database)cl.newInstance();
        DatabaseManager.registerDatabase(database);

	// Obtain the collection and launch the query, obtaining a set o results. 	    
        Collection col = DatabaseManager.getCollection(URI);
        XQueryService service = (XQueryService) col.getService("XQueryService", "1.0");
	ResourceSet result = service.query("//photo");
	    
	// Iterate through the set of results, which are XML elements of type photo 
	// (note that the resources are taken as XMLResources!). 
	// Each XMLResource is processed by the SAX handler (we provide the handler 
	// with a new Photo object so it can store the parsed information).
	// The obtained objects are stored in the HashMap photos. 
	ResourceIterator i = result.getIterator();
	while(i.hasMoreResources()) {
	        XMLResource r = (XMLResource) i.nextResource();
		Photo ph = new Photo();
		PhotoHandler handler = new PhotoHandler(ph);
		r.getContentAsSAX(handler);
		photos.put(ph.getId(), ph);
        }
	
	// Print the photo objects we have obtained
	List<String> phs = new ArrayList<String>(photos.keySet());
	Collections.sort(phs);
	for(Iterator iterator = phs.iterator(); iterator.hasNext();) {
	    String id = (String)iterator.next();
	    System.out.println(photos.get(id));
	}
	    
    }
}
